package com.lianniu.web.tea.token.service;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.lianniu.web.tea.token.dao.TeaAccessTokenDao;
import com.lianniu.web.tea.token.model.TeaAccessToken;

@Service
@Transactional
public class TeaAccessTokenService {

	private final static Logger logger = Logger.getLogger(TeaAccessTokenService.class);

	@Autowired
	private TeaAccessTokenDao teaAccessTokenDao;

	public String getAccessToken() {
		TeaAccessToken accessToken = teaAccessTokenDao.getAccessTocken();
		return accessToken.getAccessTocken();
	}
	
	public String getJsapiTicket() {
		TeaAccessToken jsapiTicket = teaAccessTokenDao.getJsapiTicket();
		return jsapiTicket.getAccessTocken();
	}

	public void saveToken(TeaAccessToken accessToken,TeaAccessToken jsapiTicket) {
		accessToken.setId(UUID.randomUUID().toString().replace("-", ""));
		Date currentTime = new Date();
		SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String dateString = formatter.format(currentTime);
		accessToken.setTime(dateString);
		accessToken.setType("1");
		
		jsapiTicket.setId(UUID.randomUUID().toString().replace("-", ""));
		jsapiTicket.setTime(dateString);
		jsapiTicket.setType("2");
		teaAccessTokenDao.delete();
		teaAccessTokenDao.insert(accessToken);
		teaAccessTokenDao.insert(jsapiTicket);
	}
}
